package com.example.springsecuritydemo2.filter;

import com.alibaba.fastjson.JSON;
import com.example.springsecuritydemo2.domain.vo.LoginUser;
import com.example.springsecuritydemo2.exception.CustomerAuthenticationException;
import com.example.springsecuritydemo2.handler.LoginFailureHandler;
import com.example.springsecuritydemo2.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

// 每个Servlet请求只会执行一次
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String uri = request.getRequestURI();
            if (!uri.startsWith("/user/login")) {
                validateToken(request);
            }
        } catch (AuthenticationException e) {
            loginFailureHandler.onAuthenticationFailure(request, response, e);
        } finally {
            filterChain.doFilter(request, response);
        }
    }

    // 用于token验证
    private void validateToken(HttpServletRequest request) {
        // 获取token
        String token = request.getHeader("Authorization");
        // 验证token
        if (!StringUtils.hasText(token)) {
            throw new CustomerAuthenticationException("token为空");
        }
        String s = stringRedisTemplate.opsForValue().get("token_" + token);
        if (s == null){
            throw new CustomerAuthenticationException("token已过期");
        }

        // 校验token
        try {
            Claims claims = JwtUtil.parseJWT(token);
            String loginUserString = claims.getSubject();
            // 把字符串转为loginUser对象
            LoginUser loginUser = JSON.parseObject(loginUserString, LoginUser.class);
            System.out.println(loginUser);
            // 把验证完后的用户信息再次放入springsecurity的上下文中
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);


        } catch (Exception e) {
            throw new CustomerAuthenticationException("token校验失败");
        }
    }
}
